package com.whfc.common.face.aiot;

import com.alibaba.fastjson.JSONObject;
import com.whfc.common.face.wotu.WotuFaceApi;
import com.whfc.common.util.HttpUtil;
import com.whfc.common.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClasssName AiotFaceApi
 * @Description AIOT平台调用
 * @Author hw
 * @Date 2021/2/25 9:12
 * @Version 1.0
 */
public class AiotFaceApi {

    private static final Logger logger = LoggerFactory.getLogger(WotuFaceApi.class);

    private final static String accessKey = "BE8B4A86B4824E87B79D137D93B80EE7";

    private final static String appSecret = "9F9DFDE86E4D469EACF32FD2AA8F2E11";

    private final static String SUCCESS_CODE = "DEP_SUS-1000";

    public static String auth(){
        String unixTime = System.currentTimeMillis()+"";
        String sign = sign(unixTime);
        String url = MessageFormat.format(AiotApiConst.SERVER+ AiotApiConst.AUTH_URL,accessKey,unixTime,sign);
        String respond = HttpUtil.doGet(url);
        logger.info("AiotFaceApi.auth,response:{}", respond);
        AiotApiResult<String> result = JSONObject.parseObject(respond, AiotApiResult.class);
        if(SUCCESS_CODE.equals(result.getCode())){
            return result.getData();
        }
        return null;
    }


    public static AiotApiResult<String> detect(String imageUrl, String imageBase64){
        Map<String,String> headers = new HashMap<>();
        headers.put("token",auth());
        JSONObject request = new JSONObject();
        request.put("imageUrl",imageUrl);
        request.put("imageBase64",imageBase64);
        request.put("returnLandmark",false);
        request.put("returnAttributes",false);
        request.put("rotateFlag",2);
        String respond = HttpUtil.doPost(AiotApiConst.SERVER+ AiotApiConst.FACE_DETECT_URL,request.toJSONString(),headers);
        logger.info("AiotFaceApi.detect,response:{}", respond);
        return JSONObject.parseObject(respond, AiotApiResult.class);
    }

    /**
     * 签名
     *
     * @param unixTime
     * @return
     */
    private static String sign(String unixTime) {
        String md5 = MD5Util.md5Encode(new StringBuffer(accessKey).append(unixTime).append(appSecret).toString());
        logger.info("md5:[{}]", md5);
        return md5;
    }
}
